//
//  HMOAuthViewController.swift
//  WeiBo
//
//  Created by Apple on 2017/5/30.
//  Copyright © 2017年 KY. All rights reserved.
//

import UIKit
import SVProgressHUD

//  微博登录界面
//  应用的唯一id
let AppKey = "2864597017"
//  AppSecret
let Appsecret = "bd88683075e50c0c7ce09311a4c12535"
//  成功回调页地址
let RedirectUrl = "http://www.itcast.cn"


class HMOAuthViewController: UIViewController {

    //  MARK:   --懒加载
    fileprivate lazy var webView: UIWebView = UIWebView()
    
    override func loadView() {
        //  设置代理
        webView.delegate = self
        view = webView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavUI()
        requestData()
    }
    
    //  MARK:   --设置导航栏按钮
    fileprivate func setupNavUI() {
        //  设置左边导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancelAction))
        //  设置标题
        navigationItem.title = "微博登录"
        //  设置右边导航栏按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: #selector(autoFillAction))
    }
    
    //  MARK:   --导航栏按钮点击事件
    @objc private func cancelAction() {
        //  让键盘失去第一响应者
        self.view.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    
    @objc private func autoFillAction() {
        //  执行js脚本
        webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value = 'hao123guohaibin@163.com';document.getElementById('passwd').value = 'guohaibin123';")
    }
    
    //  网络请求
    func requestData() {
        //  定义url
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(AppKey)&redirect_uri=\(RedirectUrl)")
        print(url)
        let request = URLRequest(url: url!)
        webView.loadRequest(request)
    }
    
//    //  获取accessToken
//    fileprivate func requestAccessToken(code: String) {
//        HMNetworTools.sharedTools.requestAccessToken(code: code) { (response, error) in
//            if error != nil {
//                print("网络请求异常: \(error!)")
//                return
//            }
//            guard let dic = response as? [String: Any] else {
//                print("返回的数据不是一个正确的字典格式")
//                return
//            }
//            //  字典转模型
//            let userAccount = HMUserAccount(dic: dic)
//            //  请求用户信息
//            self.requestUserInfo(userAccount: userAccount)
//        }
//    }
//    
//    //  获取用户信息
//    fileprivate func requestUserInfo(userAccount: HMUserAccount) {
//        HMNetworTools.sharedTools.requestUserInfo(accessToken: userAccount.access_token!, uid: userAccount.uid) { (response, error) in
//            if error != nil {
//                print("网络异常: \(error!)")
//                return
//            }
//            guard let dic = response as? [String: Any] else {
//                print("返回的数据不是一个正确的字典格式")
//                return
//            }
//            userAccount.name = dic["name"] as? String
//            userAccount.avatar_large = dic["avatar_large"] as? String
//            
//            //  归档用户数据
//            userAccount.saveUserAccount()
//        }
//    }


}

//  MARK:   --UIWebViewDelegate
extension HMOAuthViewController: UIWebViewDelegate {
    
    //  将要开始加载
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        if request.url?.absoluteString.hasPrefix(RedirectUrl) == true {
            //  不需要加载
            //  判断参数名是否是code
            if let query = request.url?.query, query.hasPrefix("code=") {
                //  获取code的参数的值
                let code = query.substring(from: "code=".endIndex)
                //  获取token
//                requestAccessToken(code: code)
                HMUserAccountViewModel.sharedUserAccount.requestAccessToken(code: code, callBack: { (isSuccess) in
                    if isSuccess {
                        print("登录成功")
                        //  切换根视图控制器
                        self.dismiss(animated: false, completion: { 
                            //  发送通知
                            NotificationCenter.default.post(name: NSNotification.Name(SwitchRootVCNotificationName), object: self)
                        })
                    } else {
                        print("登录失败")
                    }
                })
            } else {
                //  不是code这个参数名，也就是取消授权
                dismiss(animated: true, completion: nil)
            }
            return false
        } else {
            //  不是我们关心的让其加载
            return true
        }
        
    }
    //  已经开始加载
    func webViewDidStartLoad(_ webView: UIWebView) {
        SVProgressHUD.show()
    }
    //  加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //  加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        SVProgressHUD.dismiss()
    }
    
}


